/* split.c - Splits the string into a list of strings */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char **
split(char *str, const char *sep)
{
  int i;
  int max = 2;
  char *tok = NULL;
  char **res = NULL;

  res = malloc(sizeof(char *) * max);
  for (tok = strtok(str, sep), i=0; tok; tok = strtok(NULL, sep), i++) {
    if (i == (max-1)) {
      max *= 2;
      res = realloc(res, sizeof(char *) * max);
    }
    res[i] = tok;
  }
  return res;
}

char **
split_n(char *str, const char *sep, int n)
{
  int i;
  char **res = NULL;
  char *tok = NULL;
  char *rest = NULL;

  res = malloc(sizeof(char *) * n + 1);
  if (n == 0) {
    res[0] = str;
    return res;
  }
  tok = strtok(str, sep);
  res[0] = tok;
  for (i=1; i < n; i++) {
    tok = strtok(NULL, sep);
    res[i] = tok;
  }
  rest = strtok(NULL, "");
  res[i] = rest;
  return res;
}

int
main(int argc, char *argv[])
{
  char *str = NULL;
  char *sep = " \t";
  char **list_str = NULL;
  char **s;
  int n;

  if (argc == 1) {
    puts("usage: split <string> [<sep>] [<n>]");
    return 0;
  }

  if (argc > 1)
    str = strdup(argv[1]);
  if (argc > 2)
    sep = argv[2];
  if (argc > 3) {
    n = atoi(argv[3]);
    list_str = split_n(str, sep, n);
  } else
    list_str = split(str, sep);

  for (s=list_str, n=0; *s; s++, n++)
    puts(*s);

  if (argc > 1)
    free(str);

  return n;
}
